package toy.keli.edic.data.file

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import toy.keli.edic.ui.main.extend.bgRun
import java.io.IOException

class Net {
    object config{
        val host="http://picmap.online"
        object url{
            val lostWords = host+"/lostWords"
        }
    }
    companion object {
        fun nRun(func:Net.()->Unit){
            bgRun {
                try{
                    func.invoke(Net())
                }catch (e:Exception){
                    e.printStackTrace()
                }
            }
        }
        /**
         * 推送缺失的单词列表到服务器
         */
        fun putLostAll(losts: Array<String>) {
            nRun{
                post(config.url.lostWords,mapOf(
                    "id" to "",
                    "words" to losts.joinToString(",")
                ))
            }
        }
    }

    fun post(uri:String,data:Map<String,String>){
        val client = OkHttpClient()
        val request = Request.Builder().url(uri).post(data.toFormBody()).build()

        client.newCall(request).execute().use { response ->
            //if (!response.isSuccessful) throw IOException("Unexpected code $response")
            var textData = response.body?.string() ?: ""
            Log("net","put.log").add(uri,textData)
        }

    }
}

private fun <K, V> Map<K, V>.toFormBody(): RequestBody {
    return FormBody.Builder().apply {
        forEach { item->
            add(item.key.toString(), item.value.toString())
        }
    }.build()
}
